package bma.common.langutil.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

public class HttpClientUtils {
	
	private static final Log log = LogFactory.getLog(HttpClientUtils.class);
	
	private ThreadSafeClientConnManager cm = null;
	
	private int maxTotal = 100;
	
	private int defaultMaxConnection = 100;
	
	private int connectTimeOut = 3000;// 3000ms
	
	public void init(){
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
				.getSocketFactory()));
		cm = new ThreadSafeClientConnManager(schemeRegistry);
		try {
			cm.setMaxTotal(maxTotal);
		} catch (NumberFormatException e) {
			log.error(
					"Key[httpclient.max_total] Not Found in systemConfig.properties",
					e);
		}
		// 每条通道的并发连接数设置（连接池）
		try {
			cm.setDefaultMaxPerRoute(defaultMaxConnection);
		} catch (NumberFormatException e) {
			log.error(
					"Key[httpclient.default_max_connection] Not Found in systemConfig.properties",
					e);
		}
	}

	public HttpClient getHttpClient() {
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
				HttpVersion.HTTP_1_1);
		params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getConnectTimeOut()); // 3000ms
		return new DefaultHttpClient(cm, params);
	}
	
	public String convertStreamToString(InputStream is) {      
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));      
        StringBuilder sb = new StringBuilder();      
       
        String line = null;      
        try {      
            while ((line = reader.readLine()) != null) {  
                sb.append(line + "\n");      
            }      
        } catch (IOException e) {      
            e.printStackTrace();      
        } finally {      
            try {      
                is.close();      
            } catch (IOException e) {      
               e.printStackTrace();      
            }      
        }      
        return sb.toString();      
    }  

	public void release() {
		if (cm != null) {
			cm.shutdown();
		}
	}

	public void setDefaultMaxConnection(int defaultMaxConnection) {
		this.defaultMaxConnection = defaultMaxConnection;
	}

	public int getDefaultMaxConnection() {
		return defaultMaxConnection;
	}

	public void setMaxTotal(int maxTotal) {
		this.maxTotal = maxTotal;
	}

	public int getMaxTotal() {
		return maxTotal;
	}

	public void setConnectTimeOut(int connectTimeOut) {
		this.connectTimeOut = connectTimeOut;
	}

	public int getConnectTimeOut() {
		return connectTimeOut;
	}
}
